﻿using Ducu.GLB.Global;
using Ducu.SRV.ServiceInteface;
using Ducu.SRV.ViewModel.Plan;
using Ducu.SRV.ViewModel.Plan.EditorTemplates;
using Ducu.SRV.ViewModel.Plan.Shared;
using Ducu.SRV.ViewModel.Shared;
using Ducu.UI.Responsible.Filter;
using Global.Core.ExtensionMethod;
using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace Ducu.UI.Responsible.Controllers
{
    public class PlanController : BaseController
    {
        #region Constructor

        private IPlanService _planService;
        private IUserService _userService;
        public PlanController(IPlanService planService, IUserService userService)
        {
            _planService = planService;
            _userService = userService;
        }

        #endregion

        #region Common Actions

        #region URL: /Plan/New

        [NeedLogOn]
        public ActionResult New(int? prev)
        {
            NewModel model = new NewModel
            {
                PublishContent = new _NewOrEditModel()
            };
            setDefaultForNew(model.PublishContent);
            return View(model);

        }

        [HttpPost]
        public ActionResult New(NewModel model, IList<int> daysInWeek, bool? Continue)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            if (daysInWeek.IsNullOrEmpty())
            {
                ViewBag.AtLeastOneDay = "* 至少选择一个交作业时间";
                setDefaultForNew(model.PublishContent);
                return View(model);
            }

            model.PublishContent.FulfilWeekdays = daysInWeek;
            int newPlanId = _planService.New(model, daysInWeek);

            if (Continue.HasValue)
            {
                return RedirectToAction("New", new { prev = newPlanId });
            }
            else
            {
                return RedirectToAction("Show", new { id = newPlanId });
            }

        }

        #endregion

        #region URL: /Plan/{id}

        public ActionResult Show(int id)
        {
            ShowModel model = _planService.GetShow(id);
            return View(model);
        }

        #endregion

        #region URL: /Plan/Edit/{id}

        [NeedLogOn]
        public ActionResult Edit(int id)
        {
            if (!_planService.IsCurrentUserVower(id))
            {
                return Redirect(Prepage.GetRefuseAccess());
            }

            EditModel model = _planService.GetEdit(id);
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(EditModel model, IList<int> daysInWeek, int id)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            if (daysInWeek.IsNullOrEmpty())
            {
                ViewBag.AtLeastOneDay = "* 至少选择一个交作业时间";
                model = _planService.GetEdit(id);
                return View(model);
            }

            model.Origin.FulfilWeekdays = daysInWeek;

            _planService.Edit(model.Origin, id);

            return RedirectToAction("Show", new { id = id });
        }

        #endregion

        #region URL: /Plan/Index

        public ActionResult Index(string my, string keyword, int? userId, bool due = true,
            bool expire = false, bool full = false, int pageIndex = 1)
        {
            int pageSize = 5;
            Pager queryPager = new Pager(pageSize, pageIndex);

            int sumOfItems = _planService.GetCount(due, expire, full, my, keyword, userId);
            IndexModel model = _planService.Get(due, expire, full, my, keyword, userId, queryPager);

            model.Pager = new _PagerModel
            {
                PageIndex = pageIndex,
                RowSize = 5,
                SumOfPage = queryPager.GetSumOfPage(sumOfItems)
            };

            return View(model);
        }

        [HttpPost]
        public ActionResult Index(IndexModel model, string my, string keyword, int? userId,
            bool due = true, bool expire = true, bool full = false, int pageIndex = 1)
        {
            string parameters =
                "/Plan/Index/Page-{0}?keyword={1}&due={2}&expire={3}&full={4}&my={5}&userId={6}";
            return Redirect(string.Format(
                parameters, pageIndex, model.FilterKeyword, due, expire, full, my, userId));
        }

        #endregion

        #region URL: /Plan/Hisotry/{id}

        public ActionResult History(int id)
        {
            return View();
        }

        #endregion

        #region URL: /Plan/Stop

        [NeedLogOn]
        public ActionResult Stop(int id)
        {
            _planService.Stop(id);
            return RedirectToAction("Show", "Plan", new { id = id });
        }

        #endregion

        #endregion

        #region Child Actions

        [ChildActionOnly]
        public PartialViewResult _WeekBody(int planId)
        {
            //TODO: consider to move it to TaskController later.
            //IList<_DayModel> weekDays = _planService.GetWeekChart(planId);
            //return PartialView("~/Views/Task/Shared/_WeekBody.cshtml", weekDays);
            return PartialView();
        }

        [ChildActionOnly]
        public PartialViewResult _PreviousCreated(int prev)
        {
            ShowModel showModel = _planService.GetShow(prev);
            return PartialView(showModel.PublishContent.Title);
        }

        [ChildActionOnly]
        public PartialViewResult _ShowItem(int id)
        {
            _ShowItemModel model = _planService.GetShow(id).PublishContent;
            return PartialView("~/Views/Plan/Shared/_ShowItem.cshtml", model);
        }

        [ChildActionOnly]
        public PartialViewResult _Proof(int id)
        {
            LinkModel model = _planService.GetShowItemBody(id).Proof;
            return PartialView(model);
        }

        [ChildActionOnly]
        public PartialViewResult _Fulfils(int userId)
        {
            ViewBag.UserId = userId;
            ViewBag.Sum =
                _planService.GetCount(true, false, true, "f", string.Empty, userId);
            return PartialView();
        }

        [ChildActionOnly]
        public PartialViewResult _Supervises(int userId)
        {
            ViewBag.UserId = userId;
            ViewBag.Sum =
                _planService.GetCount(false, false, true, "s", string.Empty, userId);
            return PartialView();
        }

        [ChildActionOnly]
        public PartialViewResult _IndexTitle(string my, int? userId)
        {
            if (!string.IsNullOrEmpty(my))
            {
                ViewBag.My = my;
            }
            if (userId.HasValue)
            {
                ViewBag.UserId = userId.Value;
                ViewBag.UserName = _userService.GetDisplayName(userId.Value);
            }
            return PartialView();
        }

        #endregion

        #region Ajax

        public PartialViewResult _Join(int id)
        {
            JoinResult result = _planService.Join(id);

            switch (result)
            {
                case JoinResult.Succeed:
                    return PartialView("~/Views/Plan/Shared/Join/_Successfully.cshtml");

                case JoinResult.FailForFull:
                    return PartialView("~/Views/Plan/Shared/Join/_Failed.cshtml");
            }

            //TODO: 
            throw new Exception("程序出现未知的错误。");

        }

        public PartialViewResult _ShowItemBody(int id)
        {
            //_ShowItemBodyModel model = _planService.GetShow(id).PublishContent.Body;
            _ShowItemBodyModel model = _planService.GetShowItemBody(id);
            ViewBag.Id = id;
            return PartialView("~/Views/Plan/Shared/_ShowItemBody.cshtml", model);
        }

        #endregion

        private void setDefaultForNew(_NewOrEditModel model)
        {
            model.From = DateTime.Now;
            model.FulfilWeekdays = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
            model.OptionalNumbersOfSupervisors =
                new[] { 1, 2, 3, 4, Constant.ALLOWED_MAX_SUPERVISORS_NUMBER };
        }
    }
}